package thinkingInJava.generics;
// page 409 动态类型安全
//: generics/CheckedList.java
//Using Collection.checkedList().
import java.util.*;
import thinkingInJava.typeinfo.*;

public class CheckedList {
@SuppressWarnings("unchecked")
static void oldStyleMethod(List probablyDogs) {
 probablyDogs.add(new Cat());
}	
public static void main(String[] args) {
 List<Dog> dogs1 = new ArrayList<Dog>();
 oldStyleMethod(dogs1); // Quietly accepts a Cat.由于 oldStyleMethod参数没有限制类型,所以 dogs1 可以插入 cat
 // dogs1.add(new Cat()); Error
 List<Dog> dogs2 = Collections.checkedList(
   new ArrayList<Dog>(), Dog.class);
 // Derived types work fine:
 List<Pet> pets = Collections.checkedList(
   new ArrayList<Pet>(), Pet.class);
 pets.add(new Dog());
 pets.add(new Cat());
 
 try {
   oldStyleMethod(dogs2); // Throws an exception. dogs2 被 checkedList 限制只能插入 Dog,所以插入报异常
 } catch(Exception e) {
   System.out.println(e);
 }
}
} /* Output:
java.lang.ClassCastException: Attempt to insert class typeinfo.pets.Cat element into collection with element type class typeinfo.pets.Dog
*///:~
